package com.lenovo.agricultureServer.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class DatabaseUtil {
	static SQLiteDatabase sqliteDatabase;

	public static SQLiteDatabase getDatabase(Context context) {
		if (sqliteDatabase == null) {
			DatabaseHelper dbHelper = new DatabaseHelper(context, "userDB");
			// 只有调用了DatabaseHelper的getWritableDatabase()方法或者getReadableDatabase()方法之后，才会创建或打开一个连接
			sqliteDatabase = dbHelper.getReadableDatabase();
		}
		return sqliteDatabase;
	}

	public static long insert(String username, String password,String email, Context context) {
		// 创建ContentValues对象
		ContentValues values = new ContentValues();
		// 向该对象中插入键值对，其中键是列名，值是希望插入到这一列的值，值必须和数据库当中的数据类型一致
		values.put("username", username);
		values.put("userpwd", password);
		values.put("email", email);
		SQLiteDatabase sqliteDatabase = getDatabase(context);
		// 调用insert方法，就可以将数据插入到数据库当中
		// 第一个参数:表名称
		// 第二个参数：SQl不允许一个空列，如果ContentValues是空的，那么这一列被明确的指明为NULL值
		// 第三个参数：ContentValues对象
		return sqliteDatabase.insert("user", null, values);
	}

	public static boolean query(String username, String pwd, Context context) {
		SQLiteDatabase sqliteDatabase = getDatabase(context);
		Cursor cursor = sqliteDatabase.query("user", new String[] { "username",
				"userpwd" }, "username=? and userpwd=?", new String[] {
				username, pwd }, null, null, null);
		if (cursor.moveToNext())
			return true;
		return false;
	}
	
	public static String queryUserEmail(String username, Context context) 
	{
		String email = null;
		SQLiteDatabase sqliteDatabase = getDatabase(context);
		Cursor cursor = sqliteDatabase.query("user", null, "username=?", new String[] {username}, null, null, null);
		if(cursor!=null && cursor.moveToFirst())
		{
    		email = cursor.getString(cursor.getColumnIndex("email"));
		}
		return email;
	}
	
	public static String queryUserPassword(String username, Context context) 
	{
		String password = null;
		SQLiteDatabase sqliteDatabase = getDatabase(context);
		Cursor cursor = sqliteDatabase.query("user", null, "username=?", new String[] {username}, null, null, null);
		if(cursor!=null && cursor.moveToFirst())
		{
			password = cursor.getString(cursor.getColumnIndex("userpwd"));
		}
		return password;
	}
}
